package com.tpsix.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tpsix.controller.vm.RoleVM;
import com.tpsix.domain.SysRoleDept;
import com.tpsix.datascope.DataScopeContext;
import com.tpsix.service.SysRoleDeptService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tpsix.domain.SysRole;
import com.tpsix.mapper.SysRoleMapper;
import com.tpsix.service.SysRoleService;
import org.springframework.transaction.annotation.Transactional;


@Service
@AllArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final DataScopeContext dataScopeContext;

    private final SysRoleDeptService sysRoleDeptService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrUpdate(RoleVM roleVM) {
        SysRole sysRole = new SysRole();
        sysRole.setCreated(LocalDateTime.now());
        sysRole.setUpdated(LocalDateTime.now());
        BeanUtils.copyProperties(roleVM, sysRole);

        // 更新时先删除所有对应关系
        if (Objects.nonNull(roleVM.getId())) {
            sysRoleDeptService.remove(Wrappers.<SysRoleDept>lambdaQuery().eq(SysRoleDept::getRoleId, roleVM.getId()));
        }

        // 获取数据权限范围
        List<Integer> deptIds = dataScopeContext.getDeptIds(roleVM, roleVM.getDsType());

        // 按逗号分割部门id
        String deptIdsStr = deptIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        sysRole.setDsScope(deptIdsStr);

        // 保存并返回id
        boolean save = this.saveOrUpdate(sysRole);

        int roleId = sysRole.getId();

        // 角色与部门的对应关系
        if (CollectionUtils.isNotEmpty(deptIds)) {

            List<SysRoleDept> roleDeptList = deptIds.stream()
                    .map(deptId -> {
                        SysRoleDept roleDept = new SysRoleDept();
                        roleDept.setDeptId(deptId);
                        roleDept.setRoleId(roleId);
                        return roleDept;
                    }).collect(Collectors.toList());
            sysRoleDeptService.saveBatch(roleDeptList);
        }
        return save;
    }
}
